import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
import 'package:get/get.dart';
import 'package:xingsu/page/video/model/Video_model.dart';
import 'package:xingsu/page/video/video_card.dart';
import 'package:xingsu/page/video/video_horizontal_page.dart';
import 'package:xingsu/res/colors.dart';
import 'package:xingsu/util/image_util.dart';
import 'physics.dart';
import 'viewmodel/video_viewmodel.dart';

class VideoPage extends StatefulWidget {
  final List<VideoModel> videoList;
  final int page;
  final int position;

  VideoPage(
      {required this.page, required this.position, required this.videoList});

  @override
  State<VideoPage> createState() => _VideoPageState();
}

class _VideoPageState extends State<VideoPage> with WidgetsBindingObserver {
  final PageController _pageController = PageController();

  final VideoViewModel _viewModel = Get.put(VideoViewModel());

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) async {
    if (state != AppLifecycleState.resumed) {
      _viewModel.pause();
    } else {
      _viewModel.play();
    }
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addObserver(this);

    _viewModel.videoDataList.assignAll(widget.videoList);
    _viewModel.controllers.assignAll(widget.videoList
        .map((element) =>
            VideoPlayerController.network(element.videoPlayURL ?? "")
              ..initialize()
              ..setLooping(true))
        .toList());
    _viewModel.page = widget.page;
    if (widget.position == 0) {
      _viewModel.loadVideo(0);
    } else {
      _viewModel.loadVideo(widget.position);
      Future.delayed(const Duration(milliseconds: 100), () {
        _pageController.jumpToPage(widget.position);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: Get.width,
      height: Get.height,
      child: Obx(() => InkWell(
            onTap: () {
              _viewModel.playOrPause();
            },
            child: Stack(
              children: [
                PageView.builder(
                  physics: const QuickerScrollPhysics(),
                  controller: _pageController,
                  scrollDirection: Axis.vertical,
                  itemCount: _viewModel.videoDataList.length,
                  onPageChanged: (index) {
                    _viewModel.changeVideo(index);
                  },
                  itemBuilder: (context, index) {
                    Widget currentVideo = AspectRatio(
                      aspectRatio: 16 / 9.0,
                      child: VideoPlayer(_viewModel.controllers[index]),
                    );

                    Widget video = VideoCard(
                      model: _viewModel.videoDataList[index],
                      onSingleTap: () async {},
                      video: Center(
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            currentVideo,
                            const SizedBox(
                              height: 10,
                            ),
                            InkWell(
                              onTap: () {
                                _viewModel.pause();
                                Get.to(() => VideoHorizontalPage(
                                        _viewModel.videoDataList[index]))
                                    ?.then((value) {
                                  _viewModel.play();
                                });
                              },
                              child: Center(
                                child: Container(
                                  width: 62,
                                  height: 28,
                                  alignment: Alignment.center,
                                  decoration: BoxDecoration(
                                      color: Colors.white.withOpacity(0.9),
                                      borderRadius: BorderRadius.circular(14)),
                                  child: Row(
                                    mainAxisSize: MainAxisSize.min,
                                    children: [
                                      loadAssetImage("icon_fullscreen",
                                          width: 16, height: 16),
                                      const SizedBox(
                                        width: 5,
                                      ),
                                      const Text(
                                        "全屏",
                                        style: TextStyle(
                                            color: Colours.textColor,
                                            fontSize: 13),
                                      )
                                    ],
                                  ),
                                ),
                              ),
                            )
                          ],
                        ),
                      ),
                    );
                    return video;
                  },
                ),
                _viewModel.isPlaying.value
                    ? const SizedBox()
                    : Container(
                        alignment: Alignment.center,
                        child: const Icon(
                          Icons.play_circle_fill_outlined,
                          color: Colors.white70,
                          size: 60,
                        ),
                      ),
                Padding(
                  padding: EdgeInsets.only(
                      left: 15, top: MediaQuery.of(context).padding.top + 20),
                  child: IconButton(
                    onPressed: () {
                      Get.back();
                    },
                    icon: const Icon(
                      Icons.arrow_back_ios,
                      color: Colors.white,
                      size: 24,
                    ),
                  ),
                )
              ],
            ),
          )),
    );
  }
}
